<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\CarDealer;

use AuctionCore\Other\CouponLog;
use AuctionCore\System\AuctionException;
use \AuctionCore\Common\PhpMemcache;
use AuctionCore\Common\AntNest;
use AuctionCore\Common\PhpRedis;
use AuctionCore\System\AppDevice;
use AuctionCore\Account\UniqLogin;
use AuctionCore\Account\LoginLog;
use AuctionCore\Account\FrontUser;


/**
 * 车商帐户功能类
 * @author       Administrator
 */
class  Dealer
{

    /**
     * 车商id
     * @var      int
     */
    private $dealer_id;

    /**
     * 构造,初始化"车商id"
     * @param    int $dealer_id 车商id
     * @return   void
     */
    public function __construct($dealer_id)
    {
        $this->dealer_id = $dealer_id;
    }

    /**
     * 车商基本详细
     * @return   Object
     */
    public function dealer_base_info($dealer_id=0,$uid=0)
    {
        if(empty($this->dealer_id)) $this->dealer_id = $dealer_id;
        $map = array('d.dealer_id' => array('eq', $this->dealer_id));
        //$fields = 'd.*,u.uid,u.real_name,u.user_name,u.avatar,u.sex,e.emp_id as manager_id,e.real_name manager_name,u.pwd_mobile';
        $fields = 'd.*,e.emp_id as manager_id,e.real_name manager_name';
        $prefix = C('DB_PREFIX');
        $row = M('car_dealer')->alias('d')->field($fields)
            ->join("LEFT JOIN {$prefix}dealer_user as du ON du.dealer_id=d.dealer_id")
            ->join("LEFT JOIN {$prefix}dealer_manager as dm ON d.dealer_id=dm.dealer_id")
            ->join("LEFT JOIN {$prefix}employee e ON dm.emp_id=e.emp_id")
            ->where($map)->find();

        if($row && $uid){
            $result = $this->get_userinfo($uid);
            $result['avatar'] = get_content_cdnurl().$result['avatar'];
            return array_merge($row,$result);
        }
        return $row;
    }

    /**
     * 根据uid获取用户信息
     * @param string $uid 用户id
     * @return array
     * @throws AuctionException
     */
    public  function  get_userinfo($uid = ''){
        $antnest = new AntNest(C('APP_KEY'),C('SECRET_KEY'));
        $option  = json_encode(array('account_type'=>C('ACCOUNT_TYPE'),'account_id'=>$uid));
        $info = $antnest->juhecurl(C('ANT_URL').C('USE_ROUTE.get_info_by_uid'),$option);
        $info = json_decode($info,true);
        if($info['code'] === "000000"){
            $result = array(
                'user_name'=>$info['data']['account_name'],
                'uid'=>$info['data']['account_id'],
                'pwd_password'=>$info['data']['pwd'],
                'pwd_mobile'=>$info['data']['mobile'],
                'nick_name'=>$info['data']['nick_name'],
                'real_name'=>$info['data']['real_name'],
                'avatar'=>$info['data']['account_avatar'],
                'createtime'=>$info['data']['reg_date'],
                'las_login_time'=>$info['data']['las_login_time'],
                'updatetime'=>$info['data']['last_modify_time'],
            );
            return $result;
        }
        return false;
    }

    /**
     * 短信设置详细
     * 返回短信设置详细信息
     * @return   Object
     */
    public function mob_msgset_detail()
    {
        $detail = $this->dealer_base_info();
        $types = array(
            'start_au_remind' => ''
        , 'trading_remind' => ''
        , 'arbitrate_remind' => ''
        , 'money_change_remind' => ''
        );
        $types = array_intersect_key($detail, $types);
        return $types;
    }

    /**
     * 修改短信设置
     * @param    int $msg_setting_tab 1.发起拍卖是否接收，2.交易提醒是否接收，3.仲裁提醒是否接收，4.充值保证金是否接收
     * @param    boolean $msg_setting_value 设置项值
     * @return   boolean
     */
    public function change_mob_msgset($msg_setting_tab, $msg_setting_value)
    {
        $types = array(
            '1' => 'start_au_remind'
        , '2' => 'trading_remind'
        , '3' => 'arbitrate_remind'
        , '4' => 'money_change_remind'
        );
        $info = array();
        $info[$types[$msg_setting_tab]] = $msg_setting_value;
        $ok = $this->update($info,array());
        return $ok;
    }

    /**
     * 记录车商用户设备号与极光关联数据
     * @param $option
     */
    public  function car_dealer_device($option){
        $is_set = M("car_dealer_device")->where("uid=".$option['uid']." and dealer_id=".$option['dealer_id'])->field("cdd_id,jpush_id")->find();
        if($is_set){
                if($is_set['jpush_id']!=$option['jpush_id']){
                    M("car_dealer_device")->where("uid=".$option['uid']." and dealer_id=".$option['dealer_id'])->save(array('jpush_id'=>$option['jpush_id'],'modifytime'=>date("Y-m-d H:i:s")));
                }
        } else{
            $optione['createtime'] = date("Y-m-d H:i:s");
            M("car_dealer_device")->add($option);
        }
    }

   public function update($post_info, $uid,&$error_info=array())
    {

        $dealer_id = $this->dealer_id;
        $info = $this->dealer_base_info($dealer_id,$uid);

        //开启事务
        M()->startTrans();

        $dealer = M('car_dealer');
        $ok = $dealer->where('dealer_id=\'' . $this->dealer_id . '\'')->save($post_info);
        if($ok === false){
            \Think\Log::record('更新车商信息失败');
            M()->rollback();
            return false;
        }

        //同步更新蚁巢账号信息
        $ant = new AntNest();
        $ant_account['account_id'] = $uid;
        //$ant_account['mobile'] = $post_info['contact_mobile'];  //不更新手机号信息
        $ant_account['real_name'] = $post_info['contact_person'];
        $ant_account['u_idcard'] = $post_info['dealer_idcard'];
        $ok = $ant->set_user($ant_account,$error_info);
        if($ok === false){
            \Think\Log::record('更新用户信息失败');
            M()->rollback();
            return false;
        }

        if($post_info['category']==1){
            //更新提车人
            $tm = new TakeMan($this->dealer_id);
            $man_info = $tm->get_default_man();
            $data = array();
            $data['real_name'] = $post_info['contact_person'];
            $data['sex'] = $post_info['sex'];
            $data['mobile'] = $post_info['contact_mobile'];
            $data['idcard'] = $post_info['dealer_idcard'];
            if (empty($man_info)) {
                $data['take_num'] = 0;
                $data['is_contact_person'] = 1;
                $ok = $tm->add($data);
                if(!$ok){
                    \Think\Log::record('增加提车人失败');
                    M()->rollback();
                    return false;
                }
            } else {
                $data['man_id'] = $man_info['man_id'];
                $ok = $tm->edit($data);
                if($ok === false){
                    \Think\Log::record('修改提车人失败');
                    M()->rollback();
                    return false;
                }
            }
        }
       M()->commit();
        return true;
    }

    /**查询车商的ID
     * @param $info id、 车商名、车商手机号
     * return int
     */
    public static function  car_dealer_info($info){
        $dealer = M('car_dealer');
        if(preg_match("/^1[34578]{1}\d{9}$/",$info)){
            $sql = "contact_mobile=$info";
        }
        if(!is_numeric($info)){
            $sql = "contact_person='$info'";
        }
        $id = $dealer->where($sql)->getField("dealer_id");
        return $id;
    }


    /**
     * 车商登录信息  公用方法   登录 注册
     * @param $info
     * @param $login_key
     * @param $username
     * @param $pwd
     * @param $is_ios
     * @param $uuid
     */
    public  function login_info($info, $login_key,$is_ios,$uuid,$jpush_id){
        $mem = new PhpMemcache();
        //更新互斥登录
        $ul = new UniqLogin();
        $uniq_login_token = $ul->update($info['uid']);
        $info['uniq_login_token'] = $uniq_login_token;

        //车商信息
        $info['dealer_id'] = Dealer::uid_to_dealerid($info['uid']);
        $info['dealer_info'] = $this->dealer_base_info($info['dealer_id'],$info['uid']);
        unset($info['status']);

        //记录登录请求key
        $mem->set('appapi_login_'.$login_key, $info['username'], 40);

        $info['token'] = md5($info['uniq_login_token']);

        //登录uniq_login_token
        $redis = new PhpRedis();
        $left_time = strtotime(date('Y-m-d 00:00:00',strtotime('+1 day')))-time();
        $uniq_login_token = $info['uniq_login_token'] ;
        $arr = ['uuid'=>$uuid,'uid'=>$info['uid']];
        $keyName = getRedisKeyByCode('REDIS_KEY','100003',$arr);
        $redis->set($keyName , $info['uniq_login_token'] ,$left_time);
        unset($info['uniq_login_token']);

        //记录设备id
        $dev = new AppDevice();
        $dev_info = array('dev_uuid'=>$uuid,'dev_uid'=>$info['uid'],'dev_jpush_id'=>$jpush_id);
        $ok = $dev->save($dev_info);

        //记入登录日志
        if(isset($info['uid']))
            LoginLog::save($info['uid'],($is_ios?2:1),sha1($uniq_login_token),get_client_ip());
        return $info;
    }



    //不传密码，车商登录方式
    public static function loginByLoginKey($user_name,$login_key,$time){
        try{
            //蚁巢服务
            $ant = new AntNest();
            //通过用户名获取用户密码
            $pwd = $ant->get_pwd($user_name);
            if(empty($pwd)){
                AuctionException::make_throw('200022'); //200010
            }
            $info = $ant->ant_login($user_name,$pwd);
            $pwd_md5 = $pwd ;
            if( ($info['code']==='000000') && $login_key == sha1($user_name.$pwd.$time.C('auth')['salt'])){
                $front_user = new \AuctionCore\Account\FrontUser($user_name);
                if (!$front_user->check_auth("dealer_center",$info['uid'])) {
                    AuctionException::make_throw('500057');
                }
                //123456 密码
                $info['force_repwd'] = false;
                if($login_key == sha1($user_name.md5('123456').$time.C('auth')['salt'])){
                    $info['force_repwd'] = true;
                }
                //
                $mem = new PhpMemcache();
                if($mem->get('appapi_login_'.$login_key) || (time()-($time/1000))>30){                            
                    AuctionException::make_throw('100068');      
                }

                //更新互斥登录
                $ul = new \AuctionCore\Account\UniqLogin();
                $uniq_login_token = $ul->update($info['uid']);
                $info['uniq_login_token'] = $uniq_login_token;

                //车商信息
                $info['dealer_id'] = self::uid_to_dealerid($info['uid']);
                $dealer = new Dealer($info['dealer_id']);
                $info['dealer_info'] = $dealer->dealer_base_info($info['dealer_id'],$info['uid']);
                unset($info['passwd']);
                unset($info['pwd_mobile']);
                unset($info['status']); 

                //记录登录请求key
                $mem->set('appapi_login_'.$login_key, $user_name, 40);            
                return array($info,$pwd_md5);
            }else{
               AuctionException::make_throw('200022'); 
            }
        }catch(AuctionException $e){
            if($e->getCode()=='200008'){
                AuctionException::make_throw('200022');    
            }
            AuctionException::make_throw($e->getCode()); 
        }
    }

    //uid转成车商id
    public static function uid_to_dealerid($uid)
    {
        if (is_numeric($uid)) {
            $r = M('dealer_user')->field('dealer_id')->where("uid='{$uid}'")->find();
            if ($r) {
                return $r['dealer_id'];
            }
        }
        return false;
    }

    /**
     * 添加车商信息
     * @param info array
     * @return   Object
     * @author Gran Ian
     */
    public static function create($userdata)
    {
        //通过城市CODE获取depart_id
        $branch_city = M('branch_city')->where('city_code = '.$userdata['city_code'])->field('branch_id')->find();
        if(empty($branch_city)){
            $branch_city['branch_id'] = 33;
        }
        //车商信息
        $info  = array(
            'area'=>'',
            'city'=>'',
            'status'=>1,
            'depart_id'=>$branch_city['branch_id'],
            'category'=>2,
            'bail_amount'=>0,
            'freeze_amount'=>0,
            'indemnity_amount'=>0,
            'org_code'=>'',
            'fullname'=>'',
            'shortname'=>'',
            'type'=>0,
            'contact_person'=>'',
            'email'=>'',
            'province'=>0,
            'address'=>'',
            'postcode'=>'',
            'mod_man_num'=>0,
            'dealer_idcard'=>'',
            'start_au_remind'=>0,
            'trading_remind'=>0,
            'arbitrate_remind'=>0,
            'money_change_remind'=>'',
            'is_credit'=>0,
            'conversion_time'=>'',
            'idcard_front_pic'=>'',
            'idcard_back_pic'=>'',
            'idcard_hold_pic'=>'',
            'is_three_in_one'=>'',
            'business_city'=>$userdata['city_code'],
            'createtime'=>date('Y-m-d H:i:s')
        );
        //开启事务
        M()->startTrans();
        //添加车商
        $insertID = M('car_dealer')->add($info);

        //添加客服经理
        $employee = '';
        if($userdata['cm_mobile']){
            $employee = M('employee')->where('mobile = '.$userdata['cm_mobile'])->find();
        }
        unset($userdata['cm_mobile']);
        unset($userdata['city_code']);
        if($employee){
            $dealer_manager = array('dealer_id' => $insertID, 'emp_id' => $employee['emp_id']);
            $dm_id = M('dealer_manager')->add($dealer_manager);
        }

        //出错回滚
        if ($insertID < 1  ) {
            M()->rollback();
            return false;
        }
        $ant = new AntNest();
        $status = $ant->ant_regist($userdata);
        if($status['code']==='000000'){
            $uid = $status['data']['account_id'];
            //添加到车商组
            $ugd = M('auth_group_access')->add(array('uid' => $uid, 'group_id' => 2));
            //添加车商用户关联
            $ud = M('dealer_user')->add(array('uid' => $uid, 'dealer_id' => $insertID, 'status' => 1));
        }else{
            M()->rollback();
            return $status;
        }
        M()->commit();
        return $status;
    }


    /**
     * 获取我的最高出价
     * @param int $order_id 拍单ID
     * @return array
     * */
    public function get_my_highest_price($order_id)
    {
        $price1 = M('bid_log')->where("order_id='" . $order_id . "' and dealer_id='" . $this->dealer_id . "'")->order("createtime DESC")->limit('0,1')->getField('price');
        $price2 = M('bidding_log')->where("order_id='" . $order_id . "' and dealer_id='" . $this->dealer_id . "'")->order("createtime DESC")->limit('0,1')->getField('after_price');
        if ($price2 > $price1) {
            $ret = array('bidding', $price2);
        } else {
            $ret = array('bid', $price1);
        }
        return $ret;
    }

    /**
     * 获取我的客户经理
     *
     * */
    public function my_manager()
    {
        return M('dealer_manager')->alias('dm')->field('e.*')->join(C('DB_PREFIX') . "employee e ON dm.emp_id=e.emp_id")->where("dm.dealer_id='" . $this->dealer_id . "'")->find();
    }

    /**
     *是否关注拍品
     * */
    public function is_followed($order_id)
    {
        return M('dealer_follow')->where("dealer_id='" . $this->dealer_id . "' AND order_id='" . $order_id . "'")->find();

    }

    /**
     * 我参与的拍品
     * @return array order_id 拍单ID
     * */
    public function my_joined_auction()
    {
        //获取今明两天内车商参与的拍品拍单ID
        $sql = "select distinct(o.order_id) order_id from " . C("DB_PREFIX") . "order o
                            INNER JOIN " . C("DB_PREFIX") . "order_scene os ON os.scene_id=o.scene_id
                            WHERE o.status in(3,301,4) AND os.status in(1,2) AND o.order_id in(
                            SELECT order_id FROM " . C("DB_PREFIX") . "bid_log WHERE dealer_id='" . $this->dealer_id . "' AND createtime BETWEEN '" . date('Y-m-d 00:00:00',strtotime('-1 day')) . "' AND '" . date('Y-m-d 23:59:59', strtotime('+1 day')) . "'
                            UNION
                            SELECT order_id FROM " . C("DB_PREFIX") . "bidding_log WHERE dealer_id='" . $this->dealer_id . "' AND createtime BETWEEN '" . date('Y-m-d 00:00:00',strtotime('-1 day')) . "' AND '" . date('Y-m-d 23:59:59', strtotime('+1 day')) . "'
                            )";
        $res = M()->query($sql);
        $arr = array();
        foreach ($res as $v) {
            $arr[] = $v['order_id'];
        }
        return $arr;
    }

    /**
     * 我参与的拍品统计
     *
     * */
    public function stat_joined_auction()
    {
        //只统计今天明天参与的拍品
        $list = $this->my_joined_auction();
        return count($list);
    }

    /**
     * 我关注的拍品
     *
     */
    public function my_followed_auction()
    {
        //只统计今天明天参与的拍品，竞标结束就不再关注
        $map = array();
        $map['df.dealer_id'] = $this->dealer_id;
        $map['os.starttime'] = array(array('gt', date('Y-m-d 00:00:00',strtotime('-1 day'))), array('lt', date('Y-m-d 23:59:59', strtotime('+1 day'))));
        $map['o.status'] = array('in', '3,4,301');
        $map['os.status'] = array('in', '1,2');//场次状态 -1禁用 1待拍 2拍卖中 3 完成

        $res = M('order')->alias('o')->field("o.order_id")->join(C("DB_PREFIX") . "order_scene os on os.scene_id=o.scene_id")
            ->join(C("DB_PREFIX") . "dealer_follow df ON df.order_id=o.order_id")->where($map)->select();
        //echo M()->getLastSql();
        $arr = array();
        foreach ($res as $v) {
            $arr[] = $v['order_id'];
        }
        return $arr;
    }

    /**
     * 获取出价及关注的拍单
     */
    public function get_f_j_orders($map){
        $map['os.starttime'] = array('between', array(date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59',strtotime('+1 day'))));

        $map['o.status'] = '4';
        $sql1 = M('order')->alias('o')->field("distinct(o.order_id),UNIX_TIMESTAMP(o.bidding_start_time)+IF(o.act_elapsed_time>o.est_elapsed_time,o.act_elapsed_time,o.est_elapsed_time) - UNIX_TIMESTAMP(NOW()) AS left_time")
                        ->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
                        ->where("o.order_id in(
                            SELECT order_id FROM " . C("DB_PREFIX") . "bid_log WHERE dealer_id='" . $this->dealer_id . "' AND createtime BETWEEN '".date('Y-m-d 00:00:00')."' AND '" . date('Y-m-d 23:59:59',strtotime('+1 day')) ."'
                            UNION
                            SELECT order_id FROM " . C("DB_PREFIX") . "bidding_log WHERE dealer_id='" . $this->dealer_id . "' AND createtime BETWEEN '" . date('Y-m-d 00:00:00'). "' AND '" . date('Y-m-d 23:59:59',strtotime('+1 day')) ."'
                            )")
                        ->where($map)->order("left_time,o.order_id")->select(false);
        $map['o.status'] = array('in','3,301');
        $sql2 = M('order')->alias('o')->field("distinct(o.order_id),'left_time'")
                        ->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
                        ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
                        ->where("o.order_id in(
                            SELECT order_id FROM " . C("DB_PREFIX") . "bid_log WHERE dealer_id='" . $this->dealer_id . "' AND createtime BETWEEN '".date('Y-m-d 00:00:00')."' AND '" . date('Y-m-d 23:59:59',strtotime('+1 day')) ."'
                            UNION
                            SELECT order_id FROM " . C("DB_PREFIX") . "bidding_log WHERE dealer_id='" . $this->dealer_id . "' AND createtime BETWEEN '" . date('Y-m-d 00:00:00'). "' AND '" . date('Y-m-d 23:59:59',strtotime('+1 day')) ."'
                            )")
                        ->where($map)->order("FIND_IN_SET(o.status,'301,3'),os.starttime,os.scene_id,o.bidding_start_time,o.order_id")->select(false);
        $sql = "(SELECT * FROM $sql1  AS bidding) UNION ALL (SELECT * FROM $sql2 AS bid)";
        $res = M()->query($sql);

        $arr = array();
        foreach ($res as $v) {
            $arr[] = $v['order_id'];
        }

        $map['df.dealer_id'] = $this->dealer_id;
        $map['o.status'] = '4';
        $sql1 = M('order')->alias('o')->field("distinct(o.order_id),UNIX_TIMESTAMP(o.bidding_start_time)+IF(o.act_elapsed_time>o.est_elapsed_time,o.act_elapsed_time,o.est_elapsed_time) - UNIX_TIMESTAMP(NOW()) AS left_time")
                        ->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
                        ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
                        ->join(C("DB_PREFIX") . "dealer_follow df ON df.order_id=o.order_id")
                        ->where($map)->order("left_time,o.order_id")->select(false);
        $map['o.status'] = array('in','3,301');
        $sql2 = M('order')->alias('o')->field("distinct(o.order_id),'left_time'")
                        ->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
                        ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
                        ->join(C("DB_PREFIX") . "dealer_follow df ON df.order_id=o.order_id")
                        ->where($map)->order("FIND_IN_SET(o.status,'301,3'),os.starttime,os.scene_id,o.bidding_start_time,o.order_id")->select(false);
        $sql = "(SELECT * FROM $sql1  AS bidding) UNION ALL (SELECT * FROM $sql2 AS bid)";
        $res = M()->query($sql);

        $arr1 = array();
        foreach ($res as $v) {
            if(@in_array($v['order_id'],$arr)) continue;
            $arr1[] = $v['order_id'];
        }
        $arr = array_merge($arr,$arr1);
        $arr = (is_array($arr) && $arr) ? $arr : array(0);
        return $arr;
    }

    /**
     * 我关注的拍品统计
     *
     * */
    public function stat_followed_auction()
    {
        $list = $this->my_followed_auction();
        return count($list);
    }

    /**
     * 检查是否关注
     * @param $order_id
     * @return bool|mixed
     */
    public function is_follow($order_id)
    {
        if (empty($order_id)) {
            return false;
        }
        $map = array(
            'dealer_id' => $this->dealer_id,
            'order_id' => $order_id
        );
        return M('dealer_follow')->where($map)->find();
    }

    /**
     * 添加关注
     */
    public function add_follow($order_id)
    {
        $data = array();
        $data['dealer_id'] = $this->dealer_id;
        $data['order_id'] = $order_id;
        $c = M('dealer_follow')->where("dealer_id='" . $this->dealer_id . "' and order_id='" . $order_id . "'")->find();
        if (!empty($c)) {
            AuctionException::make_throw('500060');
        }
        if (!$data['dealer_id'] || !$data['order_id']) {
            AuctionException::make_throw('500058');
        }
        return M('dealer_follow')->add($data);
    }

    /**
     * 取消关注
     */
    public function remove_follow($order_id)
    {
        $data = array();
        $data['dealer_id'] = $this->dealer_id;
        $data['order_id'] = $order_id;
        if (!$data['dealer_id'] || !$data['order_id']) {
            AuctionException::make_throw('500059');
        }

        return M('dealer_follow')->where("dealer_id='" . $this->dealer_id . "' and order_id='" . $order_id . "'")->delete();
    }

    /**
     * 车商确认跟踪记录
     * @param array $data 数据
     *
     */
    public function confirm_trace_log($data = array())
    {
        if (empty($data['order_id'])) {
            AuctionException::make_throw('700027');
        }

        $data['dealer_id'] = $this->dealer_id;
        $data['createtime'] = date('Y-m-d H:i:s');
        return M('dealer_confirm_log')->add($data);
    }

    public function detail()
    {
        return M('car_dealer')->find($this->dealer_id);
    }

    /**
     * 通过id获取车商信息
     * @param int $dealer_id
     * @return \Think\mixed
     */
    public static function getDealerById($dealer_id)
    {
        return M('car_dealer')->find((int)$dealer_id);
    }

    /**
     * 获取提车人
     * @param int $dealer_id
     */
    public static function getTakeCarMan($dealer_id)
    {
        $map = array();
        $map['dealer_id'] = array('eq', $dealer_id);
        return M('take_car_man')->where($map)->select();
    }

    /**
     * 更新车商基本信息
     * @param unknown $data
     * @return Ambigous <boolean, unknown>
     */
    public function updateDealerInfo($data)
    {
        $dealer = M('car_dealer');
        $map = array('dealer_id' => array('eq', $this->dealer_id));
        return $dealer->where($map)->save($data);
    }
    /**
     * 更新车商头像
     * @param type $data
     * @return type
     */
    public function updateDealerHead($data)
    {
        $dealer = M('user');
        $map = array('dealer_id' => array('eq', $this->dealer_id));
        $uid = M('dealer_user')->where($map)->getField('uid');
        return $dealer->where(array('uid'=>$uid))->save($data);
    }

    /**
     *获取分配给我的代金券
     */
    public function get_my_coupon()
    {
        $map = array();
        $map['dealer_id'] = array('eq', $this->dealer_id);
        $map['use_status'] = array('eq', '0');
        $res = M('dealer_coupon')->where($map)->select();
        //echo M()->getLastSql();
        return $res;
    }

    /**
     * 使用代金卷
     */
    public function do_cost_coupon($data)
    {
        $arr = array();
        //dealer_id order_id cost_type occur_time occur_money remark createtime  dealer_confirm_status
        $dealer_id = $data['dealer_id'];
        $order_id = $data['order_id'];

        //事务开始
        M()->startTrans();

        foreach ($data['coupon_ids'] as $coupon_id) {
            $coupon = M('dealer_coupon')->where("dealer_id='" . $dealer_id . "' AND coupon_id='" . $coupon_id . "'")->find();
            if($coupon['use_status'] != 0){
                AuctionException::make_throw('800012');
            }
            $coupon = M('coupon')->alias('c')->field("ct.type_name,c.amount,c.coupon_id")->join(C('DB_PREFIX') . "coupon_type ct ON ct.coupon_type_id=c.coupon_type_id")
                ->where("c.coupon_id='" . $coupon_id . "'")->find();
            $info = array();
            $info['dealer_id'] = $dealer_id;
            $info['cost_type'] = '使用';//$coupon['type_name'];
            $info['occur_money'] = $coupon['amount'];//代金卷面额
            $info['order_id'] = $order_id;
            $info['coupon_id'] = $coupon_id;
            $info['coupon_no'] = $coupon['coupon_no'];
            $info['occur_type'] = 1;
            $res = CouponLog::add($info);

            $arr[] = $res;
            //更新使用状态
            //$res1 = M('coupon')->where("coupon_id='" . $coupon['coupon_id'] . "'")->save(array('use_status' => '1'));
            //$arr[] = $res1;
            $res2 = M('dealer_coupon')->where("dealer_id='" . $dealer_id . "' AND coupon_id='" . $coupon_id . "'")->save(array('use_status' => '1'));
            $arr[] = $res2;
            if (!$res || !$res2) {
                $log = array('order_id' => $order_id, 'dealer_id' => $dealer_id, 'action' => '车商代金券消耗失败，发生金额:' . $data['amount'] . '');
                \AuctionCore\System\SystemLog::add($log);
            }
        }

        if (in_array(false, $arr)) {
            M()->rollback();
            return false;
        } else {
            M()->commit();
            return true;
        }

    }
    /**
     * 使用代金卷 去掉事务处理
     * @auther niuzhixin
     */
    public function do_cost_coupon_v151($data)
    {
        $arr = array();
        $dealer_id = $data['dealer_id'];
        $order_id = $data['order_id'];
        foreach ($data['coupon_ids'] as $coupon_id) {
            $coupon = M('dealer_coupon')->where("dealer_id='" . $dealer_id . "' AND coupon_id='" . $coupon_id . "'")->find();
            if($coupon['use_status'] != 0){
                AuctionException::make_throw('800012');
            }
            $coupon = M('coupon')->alias('c')->field("ct.type_name,c.amount,c.coupon_id")->join(C('DB_PREFIX') . "coupon_type ct ON ct.coupon_type_id=c.coupon_type_id")
                ->where("c.coupon_id='" . $coupon_id . "'")->find();
            $info = array();
            $info['dealer_id'] = $dealer_id;
            $info['cost_type'] = '使用';//$coupon['type_name'];
            $info['occur_money'] = $coupon['amount'];//代金卷面额
            $info['order_id'] = $order_id;
            $info['coupon_id'] = $coupon_id;
            $info['coupon_no'] = $coupon['coupon_no'];
            $info['occur_type'] = 1;
            $res = CouponLog::add($info);

            $arr[] = $res;
            $res2 = M('dealer_coupon')->where("dealer_id='" . $dealer_id . "' AND coupon_id='" . $coupon_id . "'")->save(array('use_status' => '1'));
            $arr[] = $res2;
            if (!$res || !$res2) {
                $log = array('order_id' => $order_id, 'dealer_id' => $dealer_id, 'action' => '车商代金券消耗失败，发生金额:' . $data['amount'] . '');
                \AuctionCore\System\SystemLog::add($log);
            }
        }
        if (in_array(false, $arr)) {
            return false;
        } else {
            return true;
        }

    }

    /**
     * 获取我最的投标价
     * */
    public function get_my_last_bid_price($order_id)
    {
        return M('bid_log')->where("order_id='" . $order_id . "' AND dealer_id='" . $this->dealer_id . "'")->order('createtime desc')->limit("0,1")->getField('price');
    }

    /**
     * 获取我最的竞拍出价
     * */
    public function get_my_last_bidding_price($order_id)
    {
        return M('bidding_log')->where("order_id='" . $order_id . "' AND dealer_id='" . $this->dealer_id . "'")->max('after_price');
    }

    /**
     * 设置客服经理
     */
    public function set_dealer_mannager($mannager_id)
    {
        $data = array(
            'dealer_id' => $this->dealer_id,
            'emp_id' => $mannager_id
        );
        return M('dealer_manager')->add();
    }

    /**
     * 更新客服经理
     */
    public function update_dealer_mannager($mannager_id)
    {
        $data = array(
            'emp_id' => $mannager_id
        );
        return M('dealer_manager')->where("dealer_id='{$this->dealer_id}'")->save($data);
    }


    //清除保证金缓存
    public static function clear_dealer_bail_cache($dealer_id){
            //清空保证金缓存
            $mem = new \AuctionCore\Common\PhpMemcache();
            $mem->rm('dealer_info_'.$dealer_id);
    }

    public function get_raffle_coupon($order_id){
        $map = array();
        $map['sc.order_id'] = array('eq', $order_id);
        $map['dc.dealer_id'] = array('eq', $this->dealer_id);
        $prefix = C("DB_PREFIX");
        $raffle_coupon = M('dealer_coupon')->alias('dc')->field('dc.coupon_no,dc.amount')
            ->join("LEFT JOIN ".$prefix."lottery_coupon as lc ON lc.coupon_id = dc.coupon_id")
            ->join("LEFT JOIN ".$prefix."scratch_card as sc ON sc.cid = lc.card_id")
            ->where($map)->select();
        return $raffle_coupon;
    }

    /**
     * 修改用户密码
     * @param $option
     * @return mixed
     */
    public function change_password($option) {
        $antnest = new AntNest(C('APP_KEY'),C('SECRET_KEY'));
        $option['account_type'] = C('ACCOUNT_TYPE');
        $info = $antnest->juhecurl(C('ANT_URL').C('USE_ROUTE.change_pwd'),json_encode($option),1);
        $info = json_decode($info,true);
        return $info;
    }
    //获取车商授信信息
    public function get_dealer_credit(){
        $map = array();
        $map['dealer_id'] = array('eq',$this->dealer_id);
        return $dealer_credit_info = M('dealer_credit_log')->where($map)->find();
    }
    /**
     * 车商基本资料修改
     * @param array $data
     * @return bool
     */
    public function edit($data=array()){
        $ret = M('car_dealer')->where(array('dealer_id'=>$this->dealer_id))->save($data);
        return $ret;
    }

    /**
     * 获取车商认证跟踪失败日志
     */
    public function get_auth_sign_fail_log(){
       $ret = M('car_dealer_certify_trace_log')->where(array('dealer_id'=>$this->dealer_id,'trace_result'=>4,'trace_type'=>4))->order("id DESC")->find();
        return $ret;
    }

    /*
     * 车商认证跟踪记录统计
     * */
    public function get_certify_log_stat(){
        $ret = M('car_dealer_certify_log')->where(array('dealer_id'=>$this->dealer_id,'certify_result'=>1))->count();
        return $ret;
    }
    /*
     * 更新认证跟踪记录
     * @param $data 更新数据
     * */
    public function update_certify_log($data){
        $ret = M('car_dealer_certify_log')->where(array('dealer_id'=>$this->dealer_id,'certify_result'=>1))->save($data);
        return $ret;
    }

    /*
     * 车商签约跟踪记录统计
     * */
    public function get_sign_log_stat(){
        $ret = M('car_dealer_sign_log')->where(array('dealer_id'=>$this->dealer_id,'sign_result'=>1))->count();
        return $ret;
    }
    /*
     * 更新签约跟踪记录
     * @param $data 更新数据
     * */
    public function update_sign_log($data){
        $ret = M('car_dealer_sign_log')->where(array('dealer_id'=>$this->dealer_id,'sign_result'=>1))->save($data);
        return $ret;
    }
    /*
     * 查询车商最后一次设置智能报价
     * @param $data 更新数据
     * */
    public function get_final_price($order_id,$dealer_id){
        $map['order_id'] = array('eq',$order_id);
        $map['dealer_id'] = array('eq',$dealer_id);
        $info = M('auto_bidding')->where($map)->order('createtime desc')->limit(1)->select();
        return $info;
    }

    /**
     * @param $option
     * @return mixed
     */
    public function check_dealer_sign($option){
        $ret = M('car_dealer')->where($option)->find();
        return $ret;
    }

    //----------------------双12帮砍活动------------------
    //查询当前车商当日是否已经发起过帮砍记录
    public function get_dealer_invite_log(){
        $time = date('Y-m-d');
        $map = array();
        $map['dealer_id'] = array('eq',$this->dealer_id);
        $map['createtime'] = array(array('egt',$time." 00:00:00"),array('elt',$time." 23:59:59"));
        $info = M("dealer_activity_invite_log")->where($map)->select();
        return $info;
    }

    public function activity_info($activity_id){
        return M('dealer_activity')->where(array('activity_id'=>$activity_id))->find();
    }
    public function get_invite_log($activity_id,$date){
        $map = array();
        $map['dealer_id'] = $this->dealer_id;
        $map['activity_id'] = $activity_id;
        $map['createtime'] = array(array('egt',$date.' 00:00:00'),array('elt',$date.' 23:59:59'));
        return M('dealer_activity_invite_log')->where($map)->find();
    }

    public function add_invite_log($data){
        $data['createtime'] = date('Y-m-d H:i:s');
        return M('dealer_activity_invite_log')->add($data);
    }
    public function get_invite_info($activity_id,$sign){
        if(!$sign) return  false;
        $map = array();
        $map['activity_id'] = $activity_id;
        $map['dealer_id'] = $this->dealer_id;
        $map['sign'] = $sign;
        $map['createtime'] = array(array('egt',date('Y-m-d').' 00:00:00'),array('elt',date('Y-m-d').' 23:59:59'));

        return M('dealer_activity_invite_log')->where($map)->find();
    }

    /**
     * 检查邀请上限
     * @param $invite_id 邀请ID
     * @return mixed
     */
    public function get_upper_limit($invite_id){
        if(!$invite_id) return false;
        return M('dealer_activity_cutdown_log')->where(array('invite_id'=>$invite_id))->count();
    }
    /**
     * 检查手机号是否帮砍过
     * @param $invite_id 邀请ID
     * @param $mobile 帮砍手机号
     * @return mixed
     */
    public function get_cutdown_info($invite_id,$mobile){
        return M('dealer_activity_cutdown_log')->where(array('invite_id'=>$invite_id,'mobile'=>$mobile))->find();
    }

    //添加帮砍信息
    public function add_cutdown_log($data){
        $data['createtime'] = date('Y-m-d H:i:s');
        return M('dealer_activity_cutdown_log')->add($data);
    }

    //
    /**
     * 更新活动信息
     * @param $activity_id
     * @param array $data
     */
    public function update_activity($activity_id,$data=array()){
        return M('dealer_activity')->where(array('activity_id'=>$activity_id))->save($data);
    }

    /**
     * 更新库存代金券数量
     * @param $activity_id
     * @param $money
     * @param $data
     * @return bool
     */
    public function update_activity_coupon($activity_id,$money,$data){
        $map = array();
        $map['activity_id']  = $activity_id;
        $map['amount'] = $money;
        return M('dealer_activity_coupon')->where($map)->save($data);
    }

    public function activity_coupon_info($activity_id,$amount){
        return M('dealer_activity_coupon')->where(array('activity_id'=>$activity_id,'amount'=>$amount))->find();
    }
    //给车商发代金券
    /**
     * @param $dealer_id
     * @param $coupon_type   代金券类型
     * @param $money        代金券面额
     */
    public function send_dealer_coupon($coupon_type,$amount){
        //
        $dealer_info = $this->detail();
        $branch_id = $dealer_info['depart_id'];
        //
        $coupon = new \AuctionCore\Other\BaseCoupon();
        //获取代金券有效期配置
        $sysConf = new \AuctionCore\System\SystemConf();
        $conf = $sysConf->getConfByName('DEALER_ACTIVITY_COUPON_VALID_D');
        $config = explode('|',$conf['value']);
        $start_date = $config[0]?$config[0]:'2016-12-13';
        $end_date   = $config[1]?$config[1]:'2016-12-31';
        //生成代金券
        $sets = array();
        $sets['emp_id'] = 0;
        $sets['type'] = $coupon_type.'_'.$amount;
        $sets['amount'] = $amount;
        $sets['start_date'] = $start_date;
        $sets['end_date'] = $end_date;
        $sets['branch_company'] = $branch_id;
        $arr = $coupon->gen($sets);

        //发放代金券
        $data = array();
        $data['coupon_type_id'] = $arr['coupon_type_id'];
        $data['coupon_type_name'] =  $arr['coupon_type_name'];
        $data['amount'] = $amount;
        $data['coupon_id'] = $arr['coupon_id'];
        $data['dealer_id'] =  $dealer_info['dealer_id'];
        $data['coupon_no'] =  $arr['coupon_no'];
        $data['start_date'] =  $start_date;
        $data['end_date'] =  $end_date;

        $res = $coupon->assign_coupon($data);

        if(!$arr || !$res){
            return false;
        }

        return true;
    }

     /*
      * 抽奖
     * 奖项数组
     * 是一个二维数组，记录了所有本次抽奖的奖项信息，
     * 其中id表示中奖等级，prize表示奖品，v表示中奖概率。
     * 注意其中的v必须为整数，你可以将对应的 奖项的v设置成0，即意味着该奖项抽中的几率是0，
     * 数组中v的总和（基数），基数越大越能体现概率的准确性。
     * 本例中v的总和为100，那么平板电脑对应的 中奖概率就是1%，
     * 如果v的总和是10000，那中奖概率就是万分之一了。
     *
     */
    public function prize_draw($a=array()){
        //检查奖池
        $redis = new PhpRedis();
        $r_key = 'dealer_activity_'.date('Ymd');
        if(!$redis->exists($r_key)){
            AuctionException::make_throw('360010');
        }
        //设置奖品及中奖概率
        $prize_arr = array(
             '1'=>array('id'=>1,'prize'=>'200','v'=>200),
             '2'=>array('id'=>2,'prize'=>'100','v'=>300),
             '3'=>array('id'=>3,'prize'=>'50','v'=>500),
             '4'=>array('id'=>4,'prize'=>'30','v'=>2500),
             '5'=>array('id'=>5,'prize'=>'20','v'=>6500),
             '6'=>array('id'=>6,'prize'=>'10','v'=>20000),
        );
        $prize_arr = $a ? $a : $prize_arr;
        $arr = array();
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['v'];
        }
        $rid = get_rand($arr); //根据概率获取奖项id
        $money = $prize_arr[$rid]['prize'];
        //获取奖池中奖品剩余数量
        $num = $redis->zscore($r_key,$money);
        if($num<=0){
            unset($prize_arr[$rid]);
            if(empty($prize_arr)){
                AuctionException::make_throw('360004');
            }
            return $this->prize_draw($prize_arr);
        }
        //更新奖池数量
        $redis->zadd('dealer_activity_'.date('Ymd'),$num-1,$money);
        return $money;
    }

    /*
     * 查询车商智能报价列表
     * @param $data 更新数据
     * */
    public function get_auto_list($params = array(),$page,$page_size){
        $map['dealer_id'] = array('eq',$this->dealer_id);
        if(!empty($params['order_id'])){
            $map['order_id'] = array('eq',$params['order_id']);
        }
        if($params['type'] != -1){
            $map['status'] = array('eq',$params['type']);
        }
        if(!empty($params['start_time']) && empty($params['end_time'])){
            $map['createtime'] = array('egt',$params['start_time'].' 00:00:00');
        }else if(!empty($params['start_time']) && !empty($params['end_time'])){
            $map['createtime'] = array(array('egt',$params['start_time'].' 00:00:00'),array('elt',$params['end_time'].' 23:59:59'));
        }else if(empty($params['start_time']) && !empty($params['end_time'])){
            $map['createtime'] = array('elt',$params['end_time'].' 23:59:59');
        }
        $result = array();
        $result['list'] = M('auto_bidding')->where($map)->limit($page_size)->page($page)->order('ab_id DESC')->select();
        $result['total'] = M('auto_bidding')->where($map)->count();
        return $result;
    }
    public function getAutoBiddingInfo($order_id,$status=1){
        return M('auto_bidding')->where(array('order_id'=>$order_id,'dealer_id'=>$this->dealer_id,'status'=>$status))->find();
    }
    
    
}

?>
